﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Xml;
using SdmxMl.Common;
using SdmxMl.Manager;
using SdmxMl.Structure;
using SdmxMl.UC;
using Telerik.WinControls;
using Telerik.WinControls.UI;

namespace SmsUsers
{
    /// <summary> Dialog to manage SMS Group adding </summary>
    public partial class DlgAddGroup : Telerik.WinControls.UI.RadForm
    {
        #region Internal Members

        private MultiLang mlName;
        private UcMlText ucMlText = null;
        private string groupFullId;

        #endregion

        #region Properties

        public CodeListType cltGroup { get; private set; }

        #endregion

        #region Constructor 

        public DlgAddGroup(string fullId, CodeListType clGrp)
        { 
            InitializeComponent();

            cltGroup = clGrp;
            groupFullId = fullId;

            ucMlText = new UcMlText();
            ucMlText.BackColor = this.BackColor;
            ucMlText.ReflectBackColor();
            mlName = new MultiLang();
            ucMlText.ML = mlName;
            comboBoxTitle.DropDownControl = ucMlText;

            FillMultiComboRepository();
        }
        #endregion

        #region Fill Repository combo

        private void FillMultiComboRepository()
        {
            Dictionary<string, string> dico = new Dictionary<string, string>();
            foreach (CodeType c in cltGroup.CodeList)
            {
                Annotation a = c.AnnotationList.GetAnnotationType("REPOSITORY");
                if (a != null && a.Url != null)
                {
                    if (dico.ContainsKey(a.Url.ToString()) == false)
                    {
                        dico.Add(a.Url.ToString(), c.Id);
                    }
                    else
                    {
                        dico[a.Url.ToString()] += ", " + c.Id;
                    }
                }
            }

            radMultiColumnCbRepository.DataSource = dico;
            radMultiColumnCbRepository.Text = string.Empty;
            radMultiColumnCbRepository.MultiColumnComboBoxElement.DropDownWidth = 642;
            radMultiColumnCbRepository.EditorControl.Columns[0].Width = 300;
            radMultiColumnCbRepository.EditorControl.Columns[1].Width = 300;
            radMultiColumnCbRepository.SelectedIndex = -1;
            radMultiColumnCbRepository.SelectedIndexChanged += new System.EventHandler(this.radMultiColumnCbRepository_SelectedIndexChanged);
        }
        #endregion

        #region Add group Event

        /// <summary>
        /// Add new Group, check & persist in registry
        /// </summary>
        /// <param name="sender"></param> <param name="e"></param>
        private void radButtonAdd_Click(object sender, EventArgs e)
        {
            mlName.UpdateForCurrentLanguage(comboBoxTitle.Text);
            if (mlName.IsEmpty || textBoxValue.Text.Trim().Length == 0 || textBoxUri.Text.Trim().Length == 0)
            {
                RadMessageBox.Show(this, "Please fills required information first!", "Caution", MessageBoxButtons.OK, RadMessageIcon.Error);
            }
            else
            {
                string uri = textBoxUri.Text.Trim();
                if (UrlValidator.IsValidUrl(uri) == false)
                    RadMessageBox.Show(this, "The registry Url is invalid!", "Caution", MessageBoxButtons.OK, RadMessageIcon.Error);
                else
                {
                    try
                    {
                        SmManager sm = new SmManager();
                        // Reserve artefact
                        SdmxMl.Multiplexor.Mux.Instance.CheckOut(SdmxArtefactType.CodeLists.ToString(), groupFullId);

                        // Get it
                        cltGroup = sm.GetArtefact(SdmxArtefactType.CodeLists, new ArtefactRefBase(groupFullId), true) as CodeListType;
                        if (cltGroup == null)
                            throw new ApplicationException("Unable to fetch group codelist");

                        // Check group undefined
                        string newGroupId = textBoxValue.Text.Trim();
                        if (cltGroup.CodeList.LocateItem(newGroupId) != null)
                            throw new ApplicationException("Group already exists : " + newGroupId);


                        // Add group
                        CodeType c = new CodeType();
                        c.Id = newGroupId;
                        c.Name = mlName;
                        Annotation a = new Annotation("REPOSITORY");
                        a.Url = new Uri(uri);
                        c.AnnotationList.Add(a);
                        cltGroup.CodeList.Add(c);

                        // Persist in registry
                        XmlDocument xDoc = sm.GetAsDocument(groupFullId);
                        SdmxMl.Multiplexor.Mux.Instance.SubmitArtefact(SdmxArtefactType.CodeLists.ToString(), 
                            groupFullId, xDoc);

                        this.DialogResult = DialogResult.OK;

                    }
                    catch (Exception ex)
                    {
                        try
                        {
                            RadMessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, RadMessageIcon.Error);
                            SdmxMl.Multiplexor.Mux.Instance.UndoCheckOut(SdmxArtefactType.CodeLists.ToString(), groupFullId);
                        }
                        catch { }
                    }
                }
            }
        }
        #endregion

        #region Navigate Event

        /// <summary> Navigate to registry page</summary>
        /// <param name="sender"></param> <param name="e"></param>
        private void buttonNavigateUri_Click(object sender, EventArgs e)
        {
            try
            {
                using (new SdmxMl.Helper.CWaitCursor())
                {
                    string uri = textBoxUri.Text.Trim();
                    if (uri.Length > 0)
                    {
                        // Try to process document
                        System.Diagnostics.Process myProc;
                        myProc = System.Diagnostics.Process.Start(uri);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region Repository selection Event

        /// <summary>Repository selection in multiCombo</summary>
        /// <param name="sender"></param> <param name="e"></param>
        private void radMultiColumnCbRepository_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (radMultiColumnCbRepository.SelectedIndex >= 0)
            {
                GridViewDataRowInfo grinfo = radMultiColumnCbRepository.SelectedItem as GridViewDataRowInfo;
                if (grinfo != null)
                    textBoxUri.Text = grinfo.Cells[0].Value.ToString();
            }
        }
        #endregion
    }
}
